<script setup>
import { ref, onMounted, defineProps } from 'vue'
import { vegeFruGetDetailAPI } from '@/services/table'
import { onLoad, onShow } from '@dcloudio/uni-app'
import {
  getSingleGardenAPI,
  deleteSingleGardenAPI,
  getRemindAPI,
  changeRemindListAPI,
  deleteSingleNoteAPI,
  getNotesAPI,
} from '@/services/garden'
import uuidv4 from 'uuid-v4'
import { addToGardenAPI } from '@/services/garden'
import dayjs from 'dayjs'
import { debounce } from '@/utils/debounce'
const list = ref(['关于', '建议', '记录', '备忘'])
const currentIndex = ref(0)
const props = defineProps({
  id: {
    type: Number,
  },
  tot: {
    type: String,
  },
})
const changeIndex = (index) => {
  currentIndex.value = index
}
const Info = ref({
  alias: '',
  des: '',
  id: '',
  light: '',
  mt: '',
  name: '',
  reproductivePeriod: '',
  soilPh: '',
  soilTypes: '',
  family: '',
  st: '',
  suggestion: '',
  url: '',
})
const checkboxValue = ref([])
const checkboxList = ref([])
const bijiList = ref([
  {
    id: '',
    idGarden: '',
    remark: '',
    url: '',
    createDate: '',
  },
])

const getInfo = async (id) => {
  let res
  if (props.tot === 'garden') res = await getSingleGardenAPI(id)
  else res = await vegeFruGetDetailAPI(id)
  Info.value = res.data
}
//每次切换到当前页面都刷新笔记页面数据
onLoad((props) => {
  if (props.tot === 'garden') {
    refreshBijiData(props.id)
  }
})
const refreshBijiData = async (id) => {
  const res = await getNotesAPI(id)
  bijiList.value = res.data
}

const goNewInfo = (item) => {
  item.name = Info.value.name
  Info.value.idGarden = props.id
  let info = JSON.stringify(item)
  console.log(info)
  uni.navigateTo({
    url: '/pages/info/newNote?info=' + info,
  })
}

const goNewInfoAdd = () => {
  uni.navigateTo({
    url: `/pages/info/newNote?name=${Info.value.name}&idGarden=${props.id}`,
  })
}
const popupAdd = ref()
const popupDelete = ref()
const name = ref() //果蔬昵称
const openAddPopup = () => {
  popupAdd.value.open()
}
const openDeletePopup = () => {
  popupDelete.value.open()
}
const addToastRef = ref()
const deleteToastRef = ref()
const addToGarden = async () => {
  // 添加到果蔬小院
  if (!name.value) {
    addToastRef.value.show({
      type: 'error',
      message: '请先给它取个名',
    })
    return
  }
  await addToGardenAPI(props.id, name.value)
  uni.switchTab({
    url: '/pages/garden/garden',
  })
}
const doubounce_addToGarden = debounce(addToGarden, 500)
//删除果蔬小院中的某个果蔬
const Delete = async () => {
  await deleteSingleGardenAPI(props.id)
  deleteToastRef.value.show({
    type: 'success',
    message: '删除成功',
    complete() {
      uni.switchTab({
        url: '/pages/garden/garden',
      })
    },
  })
}
const debounce_Delete = debounce(Delete, 500)

const loading = ref(true)
const date = ref()
onMounted(async () => {
  loading.value = true
  getInfo(props.id)
  if (props.tot === 'table') {
    list.value = ['关于', '建议']
  } else {
    //获取备忘相关记录
    let dateJs = new Date(),
      year = dateJs.getFullYear(), //获取完整的年份(4位)
      month = dateJs.getMonth() + 1, //获取当前月份(0-11,0代表1月)
      strDate = dateJs.getDate() // 获取当前日(1-31)
    month = month.toString()
    month = month.length === 1 ? '0' + month : month
    strDate = strDate.toString()
    strDate = strDate.length === 1 ? '0' + strDate : strDate
    date.value = `${year}-${month}-${strDate}`
    onChangeDate()
  }
  loading.value = false
})
//备忘日期选择
const onChangeDate = async () => {
  const res = await getRemindAPI(props.id, date.value)
  if (res.data?.contentJsonArray)
    checkboxList.value = JSON.parse(res.data.contentJsonArray).map((item) => {
      return {
        content: item,
        checked: false,
        uuid: uuidv4(), //保证唯一性
      }
    })
  else checkboxList.value = []
  console.log(checkboxList.value)
}
//新增备忘
const addNewRemind = async () => {
  checkboxList.value.push({
    content: '',
    checked: false, //被选中状态
    uuid: uuidv4(),
  })
}
//保存备忘
const saveRemindRef = ref()
const addNewRemindList = async () => {
  const list = checkboxList.value
    .filter((item) => !item.checked && item.content) //未被选中并且内容不为空需要传入后端
    .map((item) => item.content)
  const contentJsonArray = JSON.stringify(list)
  console.log(contentJsonArray)
  await changeRemindListAPI({
    contentJsonArray,
    idGarden: props.id,
    createDate: date.value,
  })
  saveRemindRef.value.show({
    type: 'success',
    message: '保存成功',
    complete() {
      onChangeDate()
    },
  })
}
//删除笔记
const deleteNote = async (id, idGarden) => {
  // e.stopPropagation() //禁止冒泡
  await deleteSingleNoteAPI(id)
  await refreshBijiData(idGarden)
}
</script>
<template>
  <view>
    <uv-loading-page
      :loading="loading"
      loading-text="加载中..."
      font-size="24rpx"
    ></uv-loading-page>
    <view style="width: 100%; height: 60vh; overflow: hidden">
      <!-- <img :src="Info.url" style="width: 100%; height: 100%; object-fit: cover" /> -->
      <image
        :src="Info.url"
        style="width: 100%; height: 100%; object-fit: cover"
        mode="aspectFill"
      />
    </view>
    <view class="bottom-box">
      <view class="name">
        <span>{{ Info.name }}</span>
      </view>
      <view class="alias">
        <span>{{ Info.alias }}</span>
      </view>
      <view class="inter">
        <view class="show-data">
          <uv-subsection
            :list="list"
            :current="currentIndex"
            mode="button"
            fontSize="26rpx"
            bold
            custom-style="height: 60rpx;border-radius: 30rpx;"
            custom-item-style="border-radius: 30rpx;"
            activeColor="black"
            @change="changeIndex"
            bgColor="#456b45"
          ></uv-subsection>
          <view class="data" style="margin-top: 20rpx">
            <view style="padding: 30rpx">
              <!-- 关于模块 -->
              <view v-if="currentIndex === 0" style="min-height: 600rpx">
                <view class="cell">分类: {{ Info.mt }}</view>
                <view class="cell">品种: {{ Info.st }}</view>
                <view class="cell">光照需求: {{ Info.light }}</view>
                <view class="cell">科属: {{ Info.family }}</view>
                <view class="cell">土壤类型: {{ Info.soilTypes }}</view>
                <view class="cell">土壤pH: {{ Info.soilPh }}</view>
                <view class="cell">生育期: {{ Info.reproductivePeriod }}</view>
                <uv-collapse @change="change" @close="close" @open="open">
                  <uv-collapse-item title="详细介绍" name="Docs guide">
                    <span class="text">{{ Info.des }}</span>
                  </uv-collapse-item>
                </uv-collapse>
              </view>
              <!-- 建议模块 -->
              <view v-if="currentIndex === 1" style="min-height: 600rpx">
                <span class="text">{{ Info.suggestion }}</span>
              </view>

              <!-- 记录模块 -->
              <view
                v-if="currentIndex === 2"
                style="
                  min-height: 600rpx;
                  display: flex;
                  flex-direction: column;
                  justify-content: space-between;
                "
              >
                <view style="display: flex; flex-direction: column; justify-content: start">
                  <view
                    @click="goNewInfo(item)"
                    class="biji"
                    v-for="item in bijiList"
                    :key="item.id"
                  >
                    <view style="font-weight: bolder; font-size: 30rpx">
                      {{ dayjs(item.createDate).format('YYYY-MM-DD') }}
                    </view>
                    <view class="">
                      {{ item.remark }}
                    </view>
                    <view class="imgview">
                      <image
                        v-if="item.url"
                        class="bijiimg"
                        :src="item.url"
                        mode="aspectFill"
                      ></image>
                    </view>
                    <image
                      class="delete"
                      src="https://crop-doctor.oss-cn-beijing.aliyuncs.com/wechat/delete.png"
                      mode="scaleToFill"
                      @click.prevent="deleteNote(item.id, item.idGarden)"
                    ></image>
                  </view>
                </view>

                <view class="innerbox" @click="goNewInfoAdd">
                  <image
                    style="width: 50rpx; height: 50rpx; margin-right: 10rpx"
                    src="https://crop-doctor.oss-cn-beijing.aliyuncs.com/wechat/edit.png"
                    mode="scaleToFill"
                  ></image>
                  <view
                    style="
                      background-color: #53a658;
                      border-radius: 15rpx;
                      height: 50rpx;
                      line-height: 50rpx;
                      width: 80%;
                      margin-left: 20rpx;
                    "
                    ><span style="margin-left: 20rpx; font-weight: bolder; color: #f2e205"
                      >记录果蔬成长情况></span
                    ></view
                  >
                </view>
              </view>
              <!-- 备忘模块 -->
              <view v-if="currentIndex === 3" style="min-height: 600rpx">
                <uv-toast ref="saveRemindRef" position="top"></uv-toast>
                <view>
                  <view class="header">
                    <view
                      style="padding-right: 10rpx; background-color: white; border-radius: 10rpx"
                    >
                      <view>
                        <uni-datetime-picker
                          type="date"
                          :clear-icon="false"
                          v-model="date"
                          :border="false"
                          @change="onChangeDate"
                        />
                      </view>
                    </view>

                    <view class="add-memo-btn" @click="addNewRemind">添加备忘</view>
                  </view>
                  <view class="footer">
                    <uv-checkbox-group
                      placement="column"
                      activeColor="#19be6b"
                      v-model="checkboxValue"
                      shape="circle"
                      borderBottom="true"
                    >
                      <uv-checkbox
                        :customStyle="{ marginBottom: '10px' }"
                        v-for="item in checkboxList"
                        :key="item.uuid"
                        labelDisabled="false"
                        :name="item.uuid"
                        @change="item.checked = !item.checked"
                      >
                        <template #default>
                          <input
                            type="text"
                            v-model="item.content"
                            style="
                              margin-left: 15rpx;
                              font-size: 25rpx;
                              display: block;
                              font-weight: bolder;
                            "
                          />
                        </template>
                      </uv-checkbox>
                    </uv-checkbox-group>
                    <view class="add-memoList-btn" @click="addNewRemindList">保存</view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="btnAdd" @click="openAddPopup()" v-if="props.tot === 'table'">
      添加到我的果蔬小院
    </view>
    <view class="btnDelete" @click="openDeletePopup()" v-else> 删除 </view>
    <!-- 添加到果蔬小院弹出层 -->
    <uv-popup ref="popupAdd" mode="center" round="20">
      <uv-toast ref="addToastRef" position="top"></uv-toast>
      <view style="width: 400rpx; height: 450rpx">
        <image
          :src="Info.url"
          style="width: 100%; height: 100%; object-fit: cover"
          mode="aspectFill"
        />
      </view>
      <view>
        <view style="margin-top: 10rpx; padding: 10rpx"
          ><uv-input
            placeholder="给它取个名字吧"
            shape="circle"
            border="surround"
            v-model="name"
          ></uv-input
        ></view>
        <view class="ok" @click="doubounce_addToGarden()"> 确认 </view>
      </view>
    </uv-popup>
    <uv-popup ref="popupDelete" mode="center" round="20">
      <uv-toast ref="deleteToastRef" position="top"></uv-toast>
      <view style="width: 290rpx; height: 70rpx; text-align: center">
        <span
          style="
            font-size: 35rpx;
            color: black;
            display: block;
            font-weight: bolder;
            padding: 10rpx;
            transform: translateY(15rpx);
          "
          >确定删除它吗?</span
        >
      </view>
      <view class="ok" @click="debounce_Delete()"> 确认 </view>
    </uv-popup>
  </view>
</template>

<style>
page {
  background-color: #327349;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.footer {
  margin-top: 20rpx;
  background-color: #53a658;
  padding: 25rpx;
  border-radius: 20rpx;
  font-weight: bolder;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  min-height: 450rpx;
}
.ok {
  width: 50%;
  padding: 8px 0;
  text-align: center;
  background-color: #1a966c;
  border-radius: 20px;
  color: #fff;
  margin: 0 auto;
  margin-top: 20rpx;
  margin-bottom: 20rpx;
}
.btnAdd {
  width: 80%;
  padding: 8px 0;
  text-align: center;
  background-color: #1a966c;
  border-radius: 20px;
  color: #fff;
  margin: 0 auto;
  position: relative;
  bottom: 10rpx;
}
.btnDelete {
  width: 35%;
  padding: 8px 0;
  text-align: center;
  background-color: rgb(158, 19, 19);
  border-radius: 20px;
  color: #fff;
  font-weight: bolder;
  margin: 0 auto;
  position: relative;
  bottom: 10rpx;
}
.cell {
  /* background-color: black; */
  /* height: 45rpx; */
  margin-bottom: 10rpx;
  font-size: 27rpx;
  font-weight: bolder;
  color: #f2e205;
  padding: 10rpx;
  background-color: #53a658;
  border-radius: 20rpx;
}

.text {
  display: inline;
  border-bottom: solid 1px #979292;
  padding-bottom: 0.1rem;
  font-weight: 400;
  color: #ffffff;
}

.data {
  height: 100%;
  width: 100%;
  border-radius: 30rpx;
  background-color: #456b45;
}

.name {
  font-size: 60rpx;
  font-weight: bolder;
  color: #f2e205;
  transform: translateY(-12rpx);
}

.alias {
  font-size: 30rpx;
  color: #f2e205;
  transform: translateY(-12rpx);
}

.bottom-box {
  background-color: #327349;
  /* height: 80vh; */
  border-radius: 30rpx 30rpx 0% 0%;
  transform: translateY(-35rpx);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.bottom-box .inter {
  background-color: white;
  border-radius: 30rpx;
  width: 90%;
  height: 80%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0px 0px 15px black;
  padding-bottom: 10px;
}

.bottom-box .show-data {
  width: 80%;
  height: 90%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.biji {
  background-color: #fff;
  border-radius: 5px;
  padding: 4px;
  margin-bottom: 10px;
  font-size: 12px;
  position: relative;
}

.botbox {
  border-radius: 15px 15px 0 0;
  background-color: #fff;
  width: 100%;
  box-sizing: border-box;
  padding: 20px 20px 50px 20px;
}

.innerbox {
  border-radius: 8px;
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  box-sizing: border-box;
  font-size: 13px;
  background-color: #fff;
  display: flex;
  flex-direction: row-reverse;
  justify-content: space-between;
  align-items: center;
}
.addbox {
  width: 100%;
  height: 50px;
  text-align: center;
  padding-top: 20px;
}
.addboximg {
  width: 50px;
  height: 100%;
}

.delete {
  width: 30px;
  height: 30px;
  position: absolute;
  right: 0;
  top: 4px;
}

.imgview {
  width: 100%;
  margin-top: 10px;
  border-radius: 20rpx;
  /* background-color: #1a966c; */
  overflow: hidden;
  /* height: 300rpx; */
  position: relative;
}
.bijiimg {
  width: 100%;
  /* height: 300rpx; */
}

.add-memo-btn {
  text-align: center;
  border-radius: 8px;
  width: 30%;
  box-sizing: border-box;
  font-size: 28rpx;
  font-weight: bolder;
  background-color: #53a658;
  float: right;
  height: 50rpx;
  line-height: 50rpx;
}

.add-memoList-btn {
  text-align: center;
  border-radius: 8px;
  width: 30%;
  box-sizing: border-box;
  font-size: 28rpx;
  font-weight: bolder;
  background-color: #327349;
  margin: 0 auto;
  height: 60rpx;
  line-height: 60rpx;
}
</style>
